package com.xixibaby.redis.login;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.xixibaby.core.auth.AuthConstant;
import com.xixibaby.core.login.LoginInfoCacheVO;
import com.xixibaby.core.login.LoginInfoVO;
import com.xixibaby.core.login.SessionCache;
import com.xixibaby.core.SuperResponse;
import com.zengtengpeng.operation.RedissonCollection;
import org.redisson.api.RMap;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Redis 登录信息缓存器
 * id name url children[{
 *     id name url children
 *
 * }]
 * @param <R>
 */
public abstract class RedisLoginInfoCache<R extends SuperResponse> implements SessionCache<R> {

    @Autowired
    private RedissonCollection redissonCollection;



    protected abstract List<String> getAuthList(Long userId, int platform);

    protected Long authCacheKeyMs(){
        return AuthConstant.ONE_HOURS;
    }


    @Override
    public  void cacheLoginInfo(R response, int platform) {
        String cacheKey = StrUtil.format("{}:{}:{}",AuthConstant.AUTH_LOGIN_SESSION,response.getId(),platform );
        String sessionId = RandomUtil.randomString(16).toUpperCase();
        //其实不需要管数据存不存在 直接保存就是了
        //每次登录都吧sessionid重置。
        LoginInfoCacheVO cache = new LoginInfoCacheVO();
        cache.setAdminAuths(this.getAuthList(response.getId(),platform));
        cache.setLoginInfoUser(JSON.toJSONString(response));
        cache.setSessionId(sessionId);
        cache.setPlatform(platform);

        LoginInfoVO loginInfoVO = new LoginInfoVO();
        loginInfoVO.setSessionId(sessionId);
        loginInfoVO.setUserId(response.getId());
        loginInfoVO.setPlatform(platform);
        response.setSessionId(loginInfoVO.toString());
        redissonCollection.setMapValues(cacheKey , Convert.convert(Map.class,cache), authCacheKeyMs());
    }

    @Override
    public void loginOut(Long userId, int platform) {
        String cacheKey = StrUtil.format("{}:{}:{}",AuthConstant.AUTH_LOGIN_SESSION,userId,platform );
        RMap<Object, Object> map = redissonCollection.getMap(cacheKey);
        String[] strings = map.keySet().stream().map(Objects::toString).toArray(String[]::new);
        map.fastRemove(strings);
    }


}
